import Vue from 'vue';
import http from './http.js';

const audioStack = [];

/** 
 * 预加载一个音频文件，小程序中必须为远程路径。
 * @method preload(remoteAudioSrc, loop, obeyMuteSwitch, paused, volume)
 * @for audio.js
 * @param {string} [remoteAudioSrc] - 远程文件半路径地址  
 * @param {boolean} [loop=true] - 循环播放
 * @param {number} [volume] - 音量 0~1
 * @returns {object} - 返回promise对象 加载完成后返回 包含当前音频的id
 */
function preload(remoteAudioSrc, loop = true, volume = 1) {
	const ifExit = audioStack.find(function(e) {
		return e.src == remoteAudioSrc
	})
	if (ifExit) {
		return new Promise(resolve => {
			resolve(ifExit)
		})
	}
	const ctx = uni.createInnerAudioContext();
	ctx.src = http.getHost() + remoteAudioSrc;
	ctx.loop = loop;
	ctx.volume = volume;
	const time = new Date().getTime();
	const audio = {
		src: remoteAudioSrc,
		ctx: ctx,
		id: time,
	};
	audioStack.push(audio);
	console.log('audioContenxt', audio)
	return new Promise(resolve => {
		setTimeout(() => {
			resolve(audio)
		}, 500)
	})
}

function play(id) {
	get(id).ctx.play();
}

function stop(id) {
	get(id).ctx.stop();
}

function get(id) {
	console.log(audioStack);
	return audioStack.find(function(e) {
		return e.id == id
	})
}

const $audio = {
	preload,
	get,
	play,
	stop
}

function init() {
	console.log("*** audio installed ***");
	Vue.prototype.$audio = {
		...$audio,
	}
}

export default {
	init,
	...$audio
}